<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users extends CI_Controller {
    public  $datah, $ids, $role, $user ;

	public function __construct()
	{		
            parent::__construct();
            $this->load->model('menu_model');
            $this->load->model('users_model');
            $this->load->helper('url');
            $this->datah['baseurl'] = base_url();
            
            session_start();
            $role = 'public';   // predefine the var 
            if (isset($_SESSION)) {
             if ( isset($_SESSION['logged_in'])) {
                $role = $_SESSION['role']; } else { $role = 'public'; } } 
            
            $this->datah['role'] = $role;   
            $this->datah['menu'] = $this->menu_model->getmenu( $role ,'users' );
          
             // LOAD LIBRARIES
            $this->load->library(array('encrypt', 'form_validation' ));

            // LOAD HELPERS
            $this->load->helper(array('form', 'xml'));
            
            $this->datah['showmenu'] = TRUE;
            
        }
        
        /*
         * Functions for the management of users
         */
 
        public function listusers () {
            $grid['users'] = $this->users_model->getuserlist('all');
            
            $grid['gridtype'] = 'users';
            $data['title'] = ucfirst('Users'); // Capitalize the first letter
            $this->datah['showmenu'] = TRUE;
            $this->load->view('templates/header', $this->datah);
            $this->load->view('admin/Listgrid', $grid);
            $this->load->view('templates/footer');
        }
        
        public function edituser ($uid) {
            $data['title'] = ucfirst('Users Edit'); // Capitalize the first letter
            $this->datah['showmenu'] = TRUE;
            $this->user['data'] = $this->users_model->getuserbyid( $uid );
            $this->user['areas'] = $this->users_model->getareas();
            $this->user['roles'] = $this->users_model->getroles();
            $this->user['groups'] = $this->users_model->getgroups();
            $this->user['uid'] = $uid;
            $this->setvalidation();
            
            if( $this->input->post('chpass') ) {
              // change the users password
              redirect('index.php/chpass/'.$uid);
            }

            if( $this->input->post('save') )  // is the login button set
            {
                if( $this->form_validation->run() == TRUE ) {  // run the validation
                   // Validation is OK
                   
                     $user = array('Name' => $this->input->post('Name'),
                            'username' => $this->input->post('username'),
                            'mobile' => $this->input->post('mobile'), 
                            'PublicName' =>  $this->input->post('PublicName'), 
                         'active' =>  $this->input->post('active'),
                     //    'areas' =>  [array('area' => $this->input->post('area'), 'areaname' => $this->input->post('areaname') ) ],
                     //    'grp' =>  $grp,
                         'level' =>  $this->input->post('level'),
                         'PublicName' =>  $this->input->post('PublicName')  );
                     $this->users_model->saveuser ($uid, $user );
                   
                   redirect(base_url().'index.php/users');
                } else {
                    // Validation Failed
                    $this->load->view('templates/header', $this->datah );
                    $this->load->view('admin/edituser', $this->user);
                    $this->load->view('templates/footer');
                    
                }
            }  else {
                    $this->load->view('templates/header', $this->datah );
                    $this->load->view('admin/edituser', $this->user);
                    $this->load->view('templates/footer');
            }   
                    
        }
        
        public function chpass( $uid ) { 
           /*
            * Initiate password Change
            */
           $cgpas['uid'] = $uid;
           $this->load->view('templates/header', $this->datah );
           $this->load->view('admin/changepass', $cgpas);
           $this->load->view('templates/footer');
       }
       
       public function passchange() {
           /*
            * Update the password in the database
            * After encrypting it
            */
           $this->form_validation->set_rules('pass', 'Password', 'required|min_length(5)');
           $this->form_validation->set_rules('pass2', 'Password Confirm', 'required|min_length(5)');
           $cgpas['uid'] = $this->input->post('uid');
           if( $this->input->post('savepass') )  // is the login button set
            {
                if( $this->form_validation->run() == TRUE ) {  // run the validation
                   // Validation is OK
                     $upass = array('passwd' => $this->encrypt->encode($this->input->post('pass')));
                     var_dump($upass);
                     $this->users_model->updatepass($cgpas['uid'], $upass );
                   
                   redirect(base_url().'index.php/users');
                } else {
                    // Validation Failed
                    $this->load->view('templates/header', $this->datah );
                    $this->load->view('admin/changepass', $cgpas);
                    $this->load->view('templates/footer');
                    
                }
            }  else {
                    $this->load->view('templates/header', $this->datah );
                    $this->load->view('admin/changepass', $cgpas);
                    $this->load->view('templates/footer');
            }   
      }
        
        
        /*
         * All funtions to deal with Properties on the system
         * 
         */
        
        public function listprop () {
            if( $this->input->post('filt') )  // is the filter button set
            {
                $mfilt = $this->input->post('filter');
                $grid['filt'] = $mfilt;
            } else {
                $mfilt = 'all';
                $grid['filt'] = 'all';
            }
            
            $this->datah['menu'] = $this->menu_model->getmenu( $this->role ,'property' );   
            $this->datah['showmenu'] = TRUE;
            $grid['property'] = $this->users_model->getproplist($mfilt);
            $grid['areas'] = $this->users_model->getareas();
            //var_dump($grid['property']);
            $grid['gridtype'] = 'prop';
            
            
            $data['title'] = ucfirst('Users'); // Capitalize the first letter
            $this->load->view('templates/header', $this->datah);
            $this->load->view('admin/Listgrid', $grid);
            $this->load->view('templates/footer');
        }
        
        public function propertyadd() {
            $this->datah['menu'] = $this->menu_model->getmenu( $_SESSION['role'] ,'property' );   
            $this->datah['showmenu'] = TRUE;
//            $areasraw = $this->users_model->getareas();
//            $usersraw = $this->users_model->getuserlist('all');
//            $streetraw = $this->users_model->liststreetbyarea($_SESSION['curarea']);
            $user['streets'] = $this->users_model->liststreetbyarea($_SESSION['curarea']);
            $user['areas'] = $this->users_model->getareas();
            $user['owners'] = $this->users_model->getuserlist('all');
            
            $this->setvalidprop();
            
            if( $this->input->post('save') )  // is the login button set
            {
                if( $this->form_validation->run() == TRUE ) {  // run the validation
                   // Validation is OK
                   $this->users_model->logerrors('Property Validation ok ', '(propertyadd)');
                    $property = array('Name' => $this->input->post('pname'),
                            'roadnum' => strtolower($this->input->post('roadnum')),
                            'street' => $this->input->post('Street'),
                            'intersect' => $this->input->post('intersect'),
                            'gps' => array('longitude' => $this->input->post('longitude'), 'latutude' => $this->input->post('latutude')),
                            'area' => array('aid' => $this->input->post('aid'), 'areaname' => $this->input->post('areaname')),
                            'Owner' => array('oid' => $this->input->post('oid'), 'Ownername' => $this->input->post('Ownername')),
                            'Notes' => [],
                            'Dwellings' => [],
                            'Occupants' => []
                             );
                    $action = $this->users_model->insertprop( $property );
                    if ($action == FALSE) { $this->users_model->logerrors('Property insert failed (propertyadd): ', $property); } 
                   
                } else {
                    // Validation Failed
                    $this->users_model->logerrors('Property Validation failed ', validation_errors() );
                    $this->datah['message'] = 'Property validation Failed';
                    $user['property'] = array('Name' => $this->input->post('pname'),
                            'roadnum' => strtolower($this->input->post('roadnum')),
                            'street' => $this->input->post('Street'),
                            'intersect' => $this->input->post('intersect'),
                            'gps' => array('longitude' => $this->input->post('longitude'), 'latutude' => $this->input->post('latutude')),
                            'area' => array('aid' => $this->input->post('aid'), 'areaname' => $this->input->post('areaname')),
                            'Owner' => array('oid' => $this->input->post('oid'), 'Ownername' => $this->input->post('Ownername')),
                            'Notes' => [],
                            'Dwellings' => [],
                            'Occupants' => []
                             );
                    $this->load->view('templates/header', $this->datah );
                    $this->load->view('admin/propadd', $user);
                    $this->load->view('templates/footer');
                    
                }
            }  else {
                 $user['property'] = array('Name' => '',
                            'roadnum' => '',
                            'street' => array('Street' => '', 'StreetName' => ''),
                            'intersect' => '',
                            'gps' => array('longitude' => 0, 'latutude' => 0),
                            'area' => array('aid' => $_SESSION['curarea'], 'areaname' => $_SESSION['curareaname']),
                            'Owner' => array('oid' => '', 'Ownername' => ''),
                            'Notes' => [],
                            'Dwellings' => [],
                            'Occupants' => []   );
                    $this->load->view('templates/header', $this->datah );
                    $this->load->view('admin/propadd', $user);
                    $this->load->view('templates/footer');
               
            }
        }
        
        public function propertyedit( $pid ) {
            /*
             * Edits an exsisting Property based on its Property _id ($pid)
             */
           // var_dump($pid);
//            $areasraw = $this->users_model->getareas();
//            $usersraw = $this->users_model->getuserlist('all');
//            $prop = $this->users_model->getpropbyid($pid);
//            // var_dump($prop);
//            $streetraw = $this->users_model->liststreetbyarea($_SESSION['curarea']);
            $user['streets'] = $this->users_model->liststreetbyarea($_SESSION['curarea']);
            $user['areas'] = $this->users_model->getareas();
            $user['owners'] = $this->users_model->getuserlist('all');
            $this->datah['menu'] = $this->menu_model->getmenu( $_SESSION['role'] ,'property' );   
            $this->datah['showmenu'] = TRUE;
            
            $this->setvalidprop();
            
            if( $this->input->post('save') )  // is the login button set
            { $this->users_model->logerrors('Property Validation ', validation_errors() );
                if( $this->form_validation->run() == TRUE ) {  // run the validation
                   // Validation is OK
                    $this->users_model->logerrors('Property Validation Success ', validation_errors() );
                     $property = array('Name' => $this->input->post('pname'),
                            'roadnum' => strtolower($this->input->post('roadnum')),
                            'street' => $this->input->post('Street'),
                            'intersect' => $this->input->post('intersect'),
                             'gps' => array('longitude' => $this->input->post('longitude'), 'latutude' => $this->input->post('latutude')),
                             'area' => array('aid' => $this->input->post('aid'), 'areaname' => $this->input->post('areaname')),
                             'Owner' => array('oid' => $this->input->post('oid'), 'Ownername' => $this->input->post('Ownername')),
                             );
                             echo 'Validation passed';
                     //var_dump($property);
                    /* Update the Property */         
                    $action = $this->users_model->updateprop($pid, $property) ; //  insertprop( $property );
                    if ( $action == FALSE ) { $this->users_model->logerrors('Update Failed (propertyedit): ', $property); } 
                    redirect(base_url());
                    
                } else {
                    // Validation Failed
                    $this->users_model->logerrors('Property Validation failed ', validation_errors() );
                    $this->datah['message'] = 'Property validation Failed';
                    $user['property'] = array('Name' => $this->input->post('pname'),
                            'roadnum' => strtolower($this->input->post('roadnum')),
                            'street' => $this->input->post('Street'),
                            'intersect' => $this->input->post('intersect'),
                            'gps' => array('longitude' => $this->input->post('longitude'), 'latutude' => $this->input->post('latutude')),
                            'area' => array('aid' => $this->input->post('aid'), 'areaname' => $this->input->post('areaname')),
                            'Owner' => array('oid' => $this->input->post('oid'), 'Ownername' => $this->input->post('Ownername')),
                            'Notes' => [],
                            'Dwellings' => [],
                            'Occupants' => []
                             );
                    $this->load->view('templates/header', $this->datah );
                    $this->load->view('admin/propedit', $user);
                    $this->load->view('templates/footer');
                    
                }
            }  else {
                 
                    $this->datah['message'] = '';
                    //var_dump($prop);
                    $user['property'] = $this->propjson( $this->users_model->GetPropertyById($pid) );
                    //$this->users_model->logerrors('Property Retrieved (propertyedit)', $pid);
                    //var_dump($user['property']);
                    $this->load->view('templates/header', $this->datah );
                    $this->load->view('admin/propedit', $user);
                    $this->load->view('templates/footer');
               
            }
        }
        
        function propjson($data) {
           // var_dump($data);
           //$this->users_model->logerrors('propjson data in', $data);
            $rprop = array('Name' => $data[0]['Name'],
                            'pid' => $data[0]['_id'],
                            'roadnum' => $data[0]['roadnum'],
                            'street' => $data[0]['street'],
                            'intersect' => $data[0]['intersect'],
                             'gps' => array('longitude' => $data[0]['gps']['longitude'], 'latutude' => $data[0]['gps']['latutude']),
                             'area' => array('aid' => $data[0]['area']['aid'], 'areaname' => $data[0]['area']['areaname']),
                             'Owner' => array('oid' => $data[0]['Owner']['oid'], 'Ownername' => $data[0]['Owner']['Ownername']),
                             'Notes' => [array($data[0]['Notes'])],
                             'Dwellings' => [array($data[0]['Dwellings'])],
                             'Occupants' => [array($data[0]['Occupants'])]
                             );
            return $rprop;
        }


        
        /*
         * All the functions for the registration of users on the site
         * 
         */
        
         public function register() {
             /* 
              * This is the second stage of the registration application
              * here we get the final details for the user and save them pending 
              * them validating their email address and then the Areaadmin 
              * processing and moderating their request
              */
            $this->load->library('email'); 
            $data['title'] = ucfirst('Register'); // Capitalize the first letter
            $this->datah['showmenu'] = FALSE;
            $areasraw = $this->users_model->getareas();
            //var_dump($areasraw);
            $this->user['areas'] = $areasraw;
            $this->setregvalidation();

            if( $this->input->post('save') )  // is the save button set
            {
                if( $this->form_validation->run() == TRUE ) {  // run the validation
                    // Validation is OK
                    $this->user['data']['Name'] = $this->input->post('Name');
                    $this->user['data']['username'] = $this->input->post('username');
                    $this->user['data']['regtypetype'] = $this->input->post('regtypetype');
                    $this->user['data']['accepttandc'] = $this->input->post('accepttandc');
                    $this->user['data']['acceptprivacy'] = $this->input->post('acceptprivacy');
                    $this->user['data']['mobile'] = $this->input->post('mobile');
                    $this->user['data']['areas'] = $this->input->post('areas');
                    $this->user['data']['address'] = $this->input->post('address');
                    $this->user['data']['IPaddress'] = $this->GetIp();
                    $this->user['data']['motivation'] = $this->input->post('motivation');
                    $this->user['data']['cancelled'] = FALSE;
                    $this->user['data']['canreason'] = '';
                    
                    $tr = $this->users_model->SaveReg( $this->user['data'] );
                    //var_dump($tr);
                    if ( $tr != FALSE ) {  //$tr should be the saved regsitration _id
                        // Send email to the administrator alerting them to the fact that there is a new registration
                        $edata['Name'] = $this->user['data']['Name'];
                        $edata['username'] = $this->user['data']['username'];
                        $edata['id'] = $tr;
                        $edata['baseurl'] = $this->datah['baseurl'];
                        //$this->users_model->logerrors($edata);
                        try { $this->adminregemail($edata); $this->users_model->logerrors('Called (adminregemail): ', $edata);} 
                            catch(Exception $e) {
                              $this->users_model->logerrors('Caught exception (adminregemail): ', $e->getMessage());
                            }
                         try { $this->userregemail($edata); $this->users_model->logerrors('Called (userregemail): ', $edata);} 
                            catch(Exception $e) {
                              $this->users_model->logerrors('Caught exception (userregemail): ', $e->getMessage());
                            }
                        $this->load->view('templates/header', $this->datah );
                        $this->users_model->logerrors( 'About to load regsucess: ', $edata );
                        $this->load->view('admin/regsucess', $edata);
                        $this->load->view('templates/footer');
                        //redirect(base_url());
                   } else { redirect(base_url()); }

                } else {
                    // Validation Failed
                    $this->user['data']['Name'] = $this->input->post('Name');
                    $this->user['data']['username'] = $this->input->post('username');
                    $this->user['data']['regtypetype'] = $this->input->post('regtypetype');
                    $this->user['data']['accepttandc'] = $this->input->post('accepttandc');
                    $this->user['data']['acceptprivacy'] = $this->input->post('acceptprivacy');
                    $this->user['data']['mobile'] = $this->input->post('mobile');
                    $this->user['data']['areas'] = $this->input->post('areas');
                    $this->user['data']['address'] = $this->input->post('address');
                    $this->user['data']['motivation'] = $this->input->post('motivation');
                    $this->user['data']['IPaddress'] = $this->input->post('IPaddress');
                    $this->user['data']['canreason'] = '';
                    //var_dump($this->user);
                    $this->load->view('templates/header', $this->datah );
                    $this->load->view('admin/register', $this->user );
                    $this->load->view('templates/footer');
                    
                }
            }  else {
                    $this->load->view('templates/header', $this->datah );
                    $this->load->view('admin/register', $this->user);
                    $this->load->view('templates/footer');
            }   
       }
       
        function adminregemail($data) {
            /*
             * This function sends an email to the administrator and the area administrator 
             * to alert them to the fact that a new registration has occured
             */
                $this->load->library('email'); 
                $emaildata['site_name'] = 'Area Community Forum';
                $emaildata['activation_period'] = 24;
                $emaildata['reg_id'] = $data['id'];
                $emaildata['Name'] = $data['Name'];
                $emaildata['username'] = $data['username'];
                $emaildata['baseurl'] = $data['baseurl'];
                
                $config['protocol'] = 'sendmail';
                $config['mailpath'] = '/usr/sbin/sendmail';
                $config['charset'] = 'iso-8859-1';
                $config['wordwrap'] = TRUE;
                $config['mailtype'] = 'html';
                $this->email->initialize($config);
                $this->email->from('cforum@kelsamfos.com', 'Community Area Forum');
                $this->email->to('anton@kelsamfos.com');
                $this->email->bcc('anton@jadc.biz');
                $this->email->subject('New registration');
                $this->email->message($this->load->view('emails/adminuserregadvice', $emaildata, TRUE));
             //   $this->email->set_alt_message($this->load->view('email/'.$type.'-txt', $data, TRUE));
                $this->email->send();
                // echo $this->email->print_debugger();
           //     $this->users_model->logerrors('adminregemail', $this->email->print_debugger());
                $this->email->clear();
            }
      function userregemail($data) {
          /*
           * Sends and email to the user after registration do that they can validate their email address
           * 
           */
                $this->load->library('email'); 
                $emaildata['site_name'] = 'Area Community Forum';
                $emaildata['activation_period'] = 24;
                $emaildata['reg_id'] = $data['id'];
                $emaildata['Name'] = $data['Name'];
                $emaildata['username'] = $data['username'];
                $emaildata['baseurl'] = $data['baseurl'];
                
                $config['protocol'] = 'sendmail';
                $config['mailpath'] = '/usr/sbin/sendmail';
                $config['charset'] = 'iso-8859-1';
                $config['wordwrap'] = TRUE;
                $config['mailtype'] = 'html';
                $this->email->initialize($config);
                $this->email->from('cforum@kelsamfos.com', 'Community Area Forum');
                $this->email->to($data['username']);
                $this->email->bcc('anton@jadc.biz');
                $this->email->subject('ACF registration');
                $this->email->message($this->load->view('emails/UserEmailConfirmAdvice', $emaildata, TRUE));
                try { $this->email->send(); } catch(Exception $e) {
                            $this->users_model->logerrors('Caught exception (userregemail.send()): ', $e->getMessage());
                        }
                $this->users_model->logerrors('userregemail', $this->email->print_debugger());
                $this->email->clear();
            }
            
      public function reginfo() {
            /* 
             * This is the start of the registration process 
             * Here we get the email address and validate that it is unique 
             * the users name and the registration type
             */
            $this->datah['showmenu'] = FALSE;
            $areasraw = $this->users_model->getareas();
            //var_dump($areasraw);
            $this->user['areas'] = $areasraw;
            if (!isset($this->user['data']['Name'])) {
                $this->user['data'] = array('Name' => '', 'username' => '', 'mobile' => '','IPaddress' => $this->GetIp() ,'areas' => array('area' => '', 'areaname' => ''), 
                'address' => '', 'motivation' => '', 'regtypetype' => '', 'accepttandc' => FALSE, 'acceptprivacy' => FALSE, 'action' => 'pending', 'canreason' => '',
                'status' => 'open', 'emailvrified' => FALSE, 'addressverified' => FALSE, 'checkedby' => array('uid' => '', 'uname' => '', 'ipaddress' => '', 'regdate' => ''));
            }
            $this->setregvalidation1();

            if( $this->input->post('next') )  // is the login button set
            {
                if( $this->form_validation->run() == TRUE ) {  // run the validation
                   // Validation is OK
                   $this->user['data']['Name'] = $this->input->post('Name');
                   $this->user['data']['username'] = $this->input->post('username');
                   $this->user['data']['regtypetype'] = $this->input->post('regtypetype');
                   $this->user['data']['accepttandc'] = $this->input->post('accepttandc');
                   $this->user['data']['acceptprivacy'] = $this->input->post('acceptprivacy');
                   $this->user['data']['IPaddress'] = $this->GetIp();
                   $this->register($this->user);
                   //redirect('index.php/register', $this->user);
                } else {
                    $this->load->view('templates/header', $this->datah );
                    $this->load->view('admin/registrationinfo', $this->user );
                    $this->load->view('templates/footer');
                }
                
                } else {
                    $this->load->view('templates/header', $this->datah );
                    $this->load->view('admin/registrationinfo', $this->user );
                    $this->load->view('templates/footer');
                }
         }
         
         public function checkemail() {
             /* 
              * This is used by the registrationinfo.php 
              * Ajax call to determin the the email is unique
              */
            if (isset($_GET['email'])) {
                $email = $_GET['email']; }
             $emailinuse = $this->users_model->checkemailun($email);
             var_dump($email);
             if ($emailinuse > 0) {
                 $info = '0';
             } else {
                 $info = '1';
             }
             echo $info;
             //return $info;
         }
         
         public function AJAXgetaddress() {
             /* 
              * This is used by the moderatereg.php 
              * Ajax call to determin the following
              *    Is the property created
              *    if it get dwellings
              *    get Occupants
              *   pnum="+pnum+"&street="+street+"&aid="+road
              * http://cforum.kelsamfos.com/index.php/AJAXgetaddress?pnum=104&street=Watercombe%20Road&aid=5124d0b806c5e53197c1564c
              */
           // var_dump(isset($_GET['road'])) ;
            
            if (isset($_GET['pnum']) && isset($_GET['street']) && isset($_GET['aid'])) {
                $data['property'] = $this->users_model->findproperty($_GET['pnum'], $_GET['street'], $_GET['aid']);
             //   echo '<script type="text/javascript"> alert("SQL : '. var_dump($data) . '"); </script>;';
              if ($data['property'] == FALSE) {
                  $ret = '<p> There is no property at this address on file, 
                          Click <strong>"Add Property"</strong> to add the property </p>';
              } else  {
                $ret = '<p><strong>Property Name :</strong> '.$data['property'][0]['Name'].' <strong>@</strong> '.$data['property'][0]['roadnum'].' '.$data['property'][0]['street'];
                $ret = $ret.'<br /><strong>Nearest Intersection : </strong>  '.$data['property'][0]['intersect'].' ';
                $ret = $ret.'<br /><strong>Notes : </strong>  '.$data['property'][0]['notes'].'</p>';
              //  $ret = $ret.'<br /> <acall onclick="getdetails()">Get Details</acall>';    
              }   
            } else { $ret = '<p>Inufficient Data </p>'; }     
            echo $ret ;
         }
         
         public function AJAXAddAddress() {
             /*
              * Call passing limited info to enable a moderator to add an address
              * pnum = Property number (roadnum)
              * street = Street Name
              * aid = Area ID
              * areaname = Area Name 
              */
             if (isset($_GET['pnum']) && isset($_GET['street']) && isset($_GET['aid'])) {
                
                $prop = array("Name" => $_GET['pnum']." ".$_GET['street'], "roadnum" => $_GET['pnum'], "street" => $_GET['street'], 
                    "intersect" => $_GET['street'], "gps" => array( "longitude" => 0, "latutude" => 0 ), "area" => array( "aid" => $_GET['aid'], 
                            "areaname" => $_GET['areaname'] ), "Owner" => array( "oid" => "", "Ownername" => "" ), 
                                    "Notes" => [array("Added by ".$_SESSION['Name']) ], 'Dwellings' => [],
                            'Occupants' => [] );
                $pid = $this->users_model->insertprop($prop);
                if ($pid == FALSE) {
                    echo 'Property was not successfully added';
                } else {
                    echo $pid.', Property added successfully';
                }
                
             }
         }
         
         public function testajax() {
             $rid = $_GET['rid'];
             $ncom = $_GET['com'];
             $_SESSION['message'] = 'TEST : '."Name :" .$_SESSION['Name']." |rid :".$rid." |comment :".$ncom; 
             echo 'TEST : '.$_SESSION['message'] ; 
         }
         
         public function AJAXAddcomment() {
             /*
              * Call adds the comment to the registration
              * rid = Registration id
              * Name = Name of the persomn making the comment
              * comment = The text of the comment
              */
             $rid = $_GET['rid'];
             $ncom = stripslashes($_GET['com']);
             if ( isset($rid) && isset($ncom) ) {
                if (strlen($ncom) > 0) {
                    $comment = array( "Name" => $_SESSION['Name'], "rid" => $rid, "comment" => $ncom );
                    $pid = $this->users_model->insertRegComment($comment);
                    if ($pid == FALSE) {
                        $t = 'comment was not successfully added';
                    } else { 
                        $t = "Ok"; 
                    }
                //   $_SESSION['message'] .= $t;
                echo $t;
                }
            }
         }
         
         public function AJAXGetComments() {
             if (isset($_GET['rid'])) {
              $pid = $this->users_model->GetRegComments($_GET['rid']);
                if ($pid == FALSE) {
                    echo "<div class='tabs'><a href='#addcomm'>Add comment</a><a href='#' onclick='getcomments();'>Refresh</a></div><br />No Comments";
                } else {
                    $commdisp = "<div class='tabs'><a href='#addcomm'>Add comment</a><a href='#' onclick='getcomments();'>Refresh</a></div>
                    <table style='background-color: #e3e3e3; color:#606061; width:100%;'>    
                    <tr> 
                    ";
                  foreach($pid as $comment) {
                     $commdisp = $commdisp."</div><tr style='background-color: #FFFFFF; color: #606061 ; ' ><td ><b>".$comment['PostedBy']."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|  ".date('d M Y H:i', $comment['PostedOn']->sec)."</b><br />"; 
                     $commdisp = $commdisp.$comment['PostName']."</td></tr>"; 
                  } 
                  $commdisp = $commdisp."</table>";
                  echo $commdisp;
                }   
             } 
         }


         public function emailvalid($key) {
             /*
              * When the user clicks on the validate email link in the email we sent them
              * they will come here and we check if there is still a valid registration for the user
              */
            
            $getregistration = $this->users_model->getregvalidbyid($key); 
            if ($getregistration != FALSE) {
                /*
                 * email validated
                 * update the database with the key emailvalidated = true
                 * show the user a page
                 */
                $getregistration = $this->users_model->uemailreg($key);
                $this->user['Name'] = $getregistration[0]['Name'];
                $this->user['username'] = $getregistration[0]['username'];
                $this->user['address'] = $getregistration[0]['address'];
                $this->user['baseurl'] = $this->datah['baseurl'];
                
                $this->load->view('templates/header', $this->datah );
                $this->load->view('admin/emailauth', $this->user );
                $this->load->view('templates/footer');
            } else {
                /*
                 * Validation failed 1 of 2 reasons, either it does not exsist (Expired) or has already been validated
                 * Query to see if the registration is on file
                 */
                $this->load->view('templates/header', $this->datah );
                $getregistration = $this->LoadRegData( $this->users_model->getregdatabyid($key) );
                //var_dump($getregistration);
                if ($getregistration == FALSE) {
                    /*
                     * No registration on file
                     */
                    $this->user['type'] = 'noreg';
                    $this->load->view('admin/emailauthfail', $this->user );
                    $this->user['baseurl'] = $this->datah['baseurl'];
                    $this->load->view('templates/footer'); 
                } else {
                    /*
                     * Registration is there but has either been cancelled or already verified
                     */
                    $this->user['type'] = 'yesreg';
                    $this->user['Name'] = $getregistration['Name'];
                    $this->user['username'] = $getregistration['username'];
                    $this->user['emailvrified'] = $getregistration['emailvrified'];
                    $this->user['status'] = $getregistration['status'];
                    $this->user['baseurl'] = $this->datah['baseurl'];
                    $this->load->view('admin/emailauthfail', $this->user );
                    $this->load->view('templates/footer'); 
                }
            }      
         }

         public function cancelreg($key) {
           /*
            * This is where the user is sent if they cleick the cancel registration
            * link in their email - this can be done any time until the registration
            * process is complete
            */
             if( $this->input->post('confirm') )  // User confirms the cancellation
            {
                // $this->cancel['cdate'] = date('j-m-y h-i-s');
                $cancel['reason'] = $this->input->post('reason');
                $cancel['status'] = 'User Cancel from Link';
                $cancel['IPaddress'] = $this->GetIp();
                $done = $this->users_model->cancelreg($key, $cancel);
                if ($done) {
                    $this->user['type'] = 'confirm';
                    $this->load->view('templates/header', $this->datah );
                    $this->load->view('admin/Showregcancel', $this->user );
                    $this->load->view('templates/footer');  
                }
            } else {
                // No post found
                $getregistration = $this->LoadRegData( $this->users_model->getregdatabyid($key) ); 
                // $this->users_model->MoveRegdata($key); 
                if ($getregistration != FALSE) { 
                    /*
                    * Registration exists
                    */
                    $status = $getregistration['status'];
                    $emailvalid = $getregistration['emailvrified'];
                    $this->user['Name'] = $getregistration['Name'];
                    $this->user['rid'] = $key;
                    $this->user['username'] = $getregistration['username'];
                    $this->user['baseurl'] = $this->datah['baseurl'];
                    $this->user['type'] = 'cancel';
                    $this->load->view('templates/header', $this->datah );
                    $this->load->view('admin/Showregcancel', $this->user );
                    $this->load->view('templates/footer');
                } else {
                redirect(base_url());
              //  var_dump($getregistration);
                }
            } 
         }
         
         public function listRegistration ($list = 'all') {
            /*
             * List Registration the $list param tells what to list
             * All = All registration on file currently (Area)
             * Valid = all those who have validated their email and can now be completed (Area)
             * Wait = all those thaty we are waiting for a response from (Area)
             * sValid = Superuser (Can see all areas)
             * sAll = Superuser Can see Current registrations regardless of area
             * sWait = all those thaty we are waiting for a response from regardless of area
             */ 
             
            $grid['area'] = $_SESSION['curarea'];
            $grid['action'] = ''; 
            
            switch ($list) {
                case 'All':
                    $grid['area'] = $_SESSION['curarea'];
                    $grid['action'] = '';
                    break;
                case 'Valid':
                    $grid['area'] = $_SESSION['curarea'];
                    $grid['action'] = 'validate';
                    break;
                case 'Wait':
                    $grid['area'] = $_SESSION['curarea'];
                    $grid['action'] = 'feedback';
                    break;
                case 'sValid':
                    $grid['area'] = '';
                    $grid['action'] = 'validate';
                    break;
                case 'sAll':
                    $grid['area'] = '';
                    $grid['action'] = '';
                    break;
                case 'sWait':
                    $grid['area'] = '';
                    $grid['action'] = 'feedback';
                    break;

                default:
                    break;
            }
            /* Update the session Variable so that the close button knows what filter was in palt */
            $_SESSION['userdata']['filt'] = $list;
            
            // var_dump($filt);
            $this->datah['menu'] = $this->menu_model->getmenu( $this->role ,'registrations' );   
            $this->datah['showmenu'] = TRUE;
            //     $grid['property'] = $this->users_model->getproplist($mfilt);
           // $grid['regdata'] = $this->users_model->getReglist($filt);
           // var_dump($grid['register']);
            //var_dump($grid['property']);
          //  $grid['gridtype'] = 'reg';
            
            $grid['baseurl'] = $this->datah['baseurl'];
            
            $data['title'] = ucfirst('Registrations'); // Capitalize the first letter
            $this->load->view('templates/header', $this->datah);
            $this->load->view('admin/listregistration', $grid);
            $this->load->view('templates/footer');
        }
        
        public function jqgetreg() {
        if (isset($_GET['area'])) {
         $filt['area'] = $_GET['area']; 
        } else {
         $filt['area'] = '';   
        } 
       
        if (isset($_GET['action'])) {
         $filt['action'] = $_GET['action']; 
        } else {
         $filt['action'] = '';   
        } 
              
        $grid = $this->users_model->getReglist($filt);
        if (count($grid) > 0) {
            header("Content-type: application/json"); 
            echo "{\"data\":" .json_encode($grid). "}";
        } else {
           header("Content-type: application/json"); 
           echo "{\"data\":" .json_encode(array('Name' => 'No Pending Registrations')). "}"; 
        }
   }
         
        
        
        function rand_passwd( $length = 8, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!£$' ) {
            /*
             * Generates an 8 letter random password
             */
            return substr( str_shuffle( $chars ), 0, $length );
        }

        public function manregbyemail() {
            /*
             * Brings up a Registration manager for the administrators to moderate 
             * the registrations (Uses the email address)
             */
             
             /* Get the Variable */ 
            
            $email = $this->input->post('username'); //$_GET['em'];
            //$_SESSION['message'] =  $email;   

            $this->setmanregvalidation();

             if( $this->input->post('save') )  {
              // if (isset($this->input->post)) {  var_dump($this->input->post);}
                if( $this->form_validation->run() == TRUE ) { 
                    /*
                     *  Validation Successfull
                     */
                    /* Save the edited registration */
                    $rid = $this->input->post('id');
                    if ( $this->input->post('addressverified') == '1' ) { $adrrverify = TRUE; } else { $adrrverify = FALSE; }
                        $regupdate = array("Name" => $this->input->post('Name'), "action" => "validate",  
                            "addressverified" => $adrrverify, "checkedby" => array( "uid" => $_SESSION['uid'], "uname" => $_SESSION['Name'], "ipaddress" => $this->GetIp(), "regdate" => new MongoDate() ), 
                            "mobile" => $this->input->post('mobile'), "status" => $this->input->post('status'), 'roadnum' => $this->input->post('roadnum'), 
                            'street' => $this->input->post('roadname'), 'role' => $this->input->post('role'));  
                        $this->users_model->updateregistration($rid, $regupdate );
                       // var_dump($this->input->post('roadname'));
                       /* 
                        * Build the insert data structure 
                        * TODO : Check condition of save and act appropriatley
                        */
                        $status = $this->input->post('status');
                        if ($status === 'accept') {
                                /* Build the user Profile */
                                /* Get the level from the role selected */
                                $this->user['roles'] = $this->users_model->getroles(2);
                                $level = $this->getrolelevel($this->input->post('role'), $this->user['roles']);
                                /* get the data again so that we have all the latest comments */
                              //  $rewrite = $this->users_model->getregdatabyid( $rid );
                                $rewrite = $this->LoadRegData( $this->users_model->getregdatabyid( $rid ) );
                                // Generate a temp password
                                try {
                                    $newpass = $this->rand_passwd(); 
                                    $upass = $this->encrypt->encode($newpass);
                                } catch (Exception $e)  {  
                                    throw new Exception( 'Something really gone wrong', 0, $e); 
                                    $newpass = $this->rand_passwd(); 
                                    $upass = $newpass;
                                }  
                                $NewUser = array("Name" => $rewrite['Name'] , 
                                'PublicName' => '' ,    
                                "active" => true, 
                                "areas" => [array("area" => $rewrite['areas']['aid'],"areaname" => $rewrite['areas']['areaname'] )], 
                                "created" => new MongoDate() , 
                                "grp" => [ ], 
                                "level" => $level, 
                                "mobile" => $rewrite['mobile'], 
                                "passwd" => $upass, 
                                "passchange" => TRUE,   
                                "role" => $rewrite['role'], 
                                "username" => $rewrite['username'], 
                                "verified" => TRUE,
                                "status" => $rewrite['status'], 
                                "audit" => $rewrite['Comments'],
                                "Comments" => []);
                               $edata['status'] =  $NewUser['status'];
                               $edata['Name'] =  $NewUser['Name'];
                               $edata['paswd'] =  $newpass;
                               $edata['username'] =  $NewUser['username'];
                               $edata['areaname'] =  $NewUser['areas']['areaname'];
                               $edata['role'] =  $NewUser['role'];
                               $edata['site_name'] = 'Area Community Forum';
                               $edata['activation_period'] = 24;
                               $edata['baseurl'] = $this->datah['baseurl'];
                               $this->emailfinalreg($edata);
                               /* Insert the new user 
                                * Email the User
                                * Move the Registration to archive 
                                * TODO : take the user back to the registration list
                                */
                                $newuser = $this->users_model->insertnewuser($NewUser);
                                $this->users_model->MoveRegdata($rid);
                                //$this->listRegistration($_SESSION['userdata']['filt']);
                                redirect(base_url().'/index.php/listRegistration/'.$_SESSION['userdata']['filt']);    
                        }           
                        redirect(base_url());         
                } else {
                    /*
                     * Validation Failed
                     */
                    $_SESSION['message'] =  'Validation Failed'; 
                     if (strlen($email) <1) { die('No email set'); }
                        $rlevel = 2;   /* Level of roles to return */
                        $this->load->library('email'); 
                        $data['title'] = ucfirst('Registration'); // Capitalize the first letter
                        $this->datah['showmenu'] = FALSE;
                        $this->user['areas'] = $this->users_model->getareas();
                        $this->user['properties'] = $this->users_model->getproplist();
                        $this->user['roles'] = $this->users_model->getroles($rlevel);
                        $this->user['regd'] = $this->LoadRegData( $this->users_model->getregbyusername($email ) );
                        $this->user['streets'] = $this->users_model->liststreetbyarea(  $this->user['regd'][0]['areas']['aid'] );

                        $this->user['rid'] = $this->user['regd']['id'];
                        $rid = $this->user['regd']['id'];
                        $this->user['regd']['Name'] = $this->input->post('Name');
                        $this->user['regd']['roadname'] = $this->input->post('roadname');
                        $this->user['regd']['roadnum'] = $this->input->post('roadnum');
                        $this->user['regd']['street'] = $this->input->post('street');
                        
                        $this->user['lsttype'] = 'all';
                        // var_dump($this->user['regd'][0]['emailvrified']);
                        if ($this->user['regd']['emailvrified']) {
                            $this->user['status'] = TRUE; // Email validated can moderate
                        } else {
                            $this->user['status'] = FALSE;  // Email not validated can not moderate
                        }
                        $this->load->view('templates/header', $this->datah);
                        $this->load->view('admin/moderatereg', $this->user);
                        $this->load->view('templates/footer');
                }
                
            }  else {
                /*
                 * No Form Submitted so display the form
                 * Get all the data we need to manage the resitrations
                 * Areas, Roles, Properties, Streets, 
                 */
                
              //  var_dump($email);
                if (strlen($email) <1) { die('No email set'); }
                $rlevel = 2;   /* Level of roles to return */
                $this->load->library('email'); 
                $data['title'] = ucfirst('Registration'); // Capitalize the first letter
                $this->datah['showmenu'] = FALSE;
                $this->user['areas'] = $this->users_model->getareas();
                $this->user['properties'] = $this->users_model->getproplist();
                $this->user['roles'] = $this->users_model->getroles($rlevel);
                $this->user['regd'] = $this->LoadRegData( $this->users_model->getregbyusername( $email ) );
                $this->user['streets'] = $this->users_model->liststreetbyarea(  $this->user['regd']['areas']['aid'] );
            
                // var_dump($this->user['streets']);
                $this->user['rid'] = $this->user['regd']['id'];
                $rid = $this->user['regd']['id'];
                $this->user['lsttype'] = 'all';
                // var_dump($this->user['regd'][0]['emailvrified']);
                if ($this->user['regd']['emailvrified']) {
                    $this->user['status'] = TRUE; // Email validated can moderate
                } else {
                    $this->user['status'] = FALSE;  // Email not validated can not moderate
                }
                $this->load->view('templates/header', $this->datah);
                $this->load->view('admin/moderatereg', $this->user);
                $this->load->view('templates/footer');
            } 
        }
        
        function LoadRegData($regddata) {
            /*
             * Take the data from the mongoread and put it into an array for the form to use
             * Returns a JSON array
             * 
             */
            $NewData = array("Name" => $regddata[0]['Name'], 
                "id" => $regddata[0]['_id'],
                "action" => $regddata[0]['action'],  
                "addressverified" => $regddata[0]['addressverified'],
                "checkedby" => array( "uid" => $regddata[0]['checkedby']['uid'], "uname" => $regddata[0]['checkedby']['uname'], "ipaddress" => $regddata[0]['checkedby']['ipaddress'], "regdate" => $regddata[0]['checkedby']['regdate'] ),
                "mobile" => $regddata[0]['mobile'],
                "status" => $regddata[0]['status'],
                'roadnum' => $regddata[0]['roadnum'], 
                'street' => $regddata[0]['street'], 
                'role' => $regddata[0]['role'],
                'IPaddress' => $regddata[0]['IPaddress'], 
                'acceptprivacy' => $regddata[0]['acceptprivacy'],
                'accepttandc'  => $regddata[0]['accepttandc'],
                'address' => $regddata[0]['address'],
                'areas' => array('aid' => $regddata[0]['areas']['aid'], 'areaname' => $regddata[0]['areas']['areaname']),
                'datesumbit' => $regddata[0]['datesumbit'],
                'motivation' => $regddata[0]['motivation'],
                'regtypetype' => $regddata[0]['regtypetype'],
                'role' => $regddata[0]['role'],
                'username' => $regddata[0]['username'],
                'emailvrified' => $regddata[0]['emailvrified'],
                'canreason' => $regddata[0]['canreason'],
                'Comments' > $regddata[0]['Comments']);
            return $NewData;
        }
        
        function emailfinalreg($edata) {
          /*
           * Sends and email to the user after registration do that they can validate their email address
           * 
           */
            $this->load->library('email'); 
            $config['protocol'] = 'sendmail';
            $config['mailpath'] = '/usr/sbin/sendmail';
            $config['charset'] = 'iso-8859-1';
            $config['wordwrap'] = TRUE;
            $config['mailtype'] = 'html';
            $this->email->initialize($config);
            $this->email->from('cforum@kelsamfos.com', 'Community Area Forum');
            $this->email->to($edata['username']);
            $this->email->bcc('anton@jadc.biz');
            $this->email->subject('ACF registration Complete');
            $this->email->message($this->load->view('emails/emailregfinal', $edata, TRUE));
            //   $this->email->set_alt_message($this->load->view('email/'.$type.'-txt', $data, TRUE));
            $this->email->send();
            // echo $this->email->print_debugger();
            $this->email->clear();
        }
        
        /*
        * Validation rules for the forms
        * 
        */
         
       function setvalidation() {
            $this->form_validation->set_rules('Name', 'Name', 'required|min_length(5)');
            $this->form_validation->set_rules('mobile', 'Mobile Number', 'required|min_length(10)|integer');
            $this->form_validation->set_rules('username', 'Email', 'required|valid_email');
            $this->form_validation->set_rules('level', 'Security Level', 'required|greater_than(-1)|less_than(10)|integer');
            $this->form_validation->set_error_delimiters('<em>','</em>');
       }
       
       function setregvalidation1() {
            $this->form_validation->set_rules('Name', 'Name', 'required|min_length(5)');
            $this->form_validation->set_rules('username', 'Email', 'required|valid_email');
//            $this->form_validation->set_rules('acceptprivacy', 'Privacy Policy', 'required');
//            $this->form_validation->set_rules('accepttandc', 'Terms and Conditions', 'required');
            $this->form_validation->set_error_delimiters('<em>','</em>');
       }
       
       function setregvalidation() {
            $this->form_validation->set_rules('mobile', 'Mobile Number', 'required|min_length(10)|integer');
            $this->form_validation->set_rules('address', 'Address', 'required||min_length(10)');
            $this->form_validation->set_error_delimiters('<em>','</em>');
       }
       
       function setvalidprop() {
            $this->form_validation->set_rules('pname', 'Property Name', 'required|min_length(5)');
            $this->form_validation->set_rules('Street', 'Street Name', 'required|min_length(3)');
            $this->form_validation->set_rules('roadnum', 'Number', 'required||min_length(1)');
            $this->form_validation->set_rules('intersect', 'Intersection', 'required||min_length(5)');
            $this->form_validation->set_rules('longitude', 'Longitude', 'greater_than(-179)|less_than(181)|numeric');
            $this->form_validation->set_rules('latitude', 'Latitude', 'greater_than(-179)|less_than(181)|numeric');
//            $this->form_validation->set_rules('accepttandc', 'Terms and Conditions', 'required');
//            $this->form_validation->set_rules('tenanttype', 'Terms and Conditions', 'required|alpha');
            $this->form_validation->set_error_delimiters('<em>','</em>');
       }
       
       function setmanregvalidation() {
           $this->form_validation->set_rules('mobile', 'Mobile Number', 'required|min_length(10)|integer');
           $this->form_validation->set_rules('Name', 'Name', 'required|min_length(5)');
        //   $this->form_validation->set_rules('street', 'Street Name', 'required|min_length(5)');
           $this->form_validation->set_rules('roadnum', 'Number', 'required||min_length(1)');
           $this->form_validation->set_error_delimiters('<em>','</em>');
       }
       

       

  
       function GetIp() {
       if (!empty($_SERVER["HTTP_CLIENT_IP"]))
        {
            //check for ip from share internet
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
            elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
            {
                // Check for the Proxy User
                $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            }
            else
                {
                    $ip = $_SERVER["REMOTE_ADDR"];
                }
            // This will print user's real IP Address
            // does't matter if user using proxy or not.
            return $ip;
   }
   
   function getrolelevel($roleid, $roles) {
      $rl = 5; 
      foreach ($roles as $r) {
         if ($r['_id'] == $roleid) {
             $rl = $r['level'];
             break;
         } 
      } 
      return $rl;
   }
   
   
   /*
    * Test
    */
     
   

  }


?>
